package cn.janyd.jmall.user.service;

import cn.janyd.common.core.vo.CommonResult;
import cn.janyd.jmall.user.convert.UserConverter;
import cn.janyd.jmall.user.dal.dataobject.user.UserDO;
import cn.janyd.jmall.user.dal.mapper.user.UserMapper;
import cn.janyd.jmall.user.manager.UserManager;
import cn.janyd.jmall.user.rpc.user.UserRpcService;
import cn.janyd.jmall.user.rpc.user.dto.UserCreateReqDTO;
import cn.janyd.jmall.user.rpc.user.dto.UserRespDTO;
import cn.janyd.jmall.user.rpc.user.dto.UserUpdateReqDTO;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.stereotype.Service;

import static cn.janyd.common.core.vo.CommonResult.success;

/**
 * @author janyd
 * @since 2020/8/10 15:24
 */
@Service
@DubboService(version = "${jmall.dubbo.versions.UserRpcService}", interfaceClass = UserRpcService.class)
public class UserServiceImpl implements UserRpcService {

    private final UserMapper userMapper;

    private final UserManager userManager;

    public UserServiceImpl(UserMapper userMapper, UserManager userManager) {
        this.userMapper = userMapper;
        this.userManager = userManager;
    }

    /**
     * 获取用户信息
     *
     * @param userId 用户ID
     * @return 用户信息
     */
    @Override
    public CommonResult<UserRespDTO> getUser(Integer userId) {
        final UserDO userDO = userMapper.selectById(userId);
        return success(UserConverter.INSTANCE.convert(userDO));
    }

    /**
     * 基于手机号码创建用户
     * 如果用户已经存在则返回用户信息
     *
     * @param userCreateReq 创建用户 DTO
     * @return 用户信息
     */
    @Override
    public CommonResult<UserRespDTO> createUserIfAbsent(UserCreateReqDTO userCreateReq) {
        UserDO user = userManager.getUser(userCreateReq.getPhone());
        if (user != null) {
            return success(UserConverter.INSTANCE.convert(user));
        }

        user = userManager.createUser(UserConverter.INSTANCE.convert(userCreateReq));
        return success(UserConverter.INSTANCE.convert(user));
    }

    @Override
    public CommonResult<Boolean> updateUser(UserUpdateReqDTO userUpdateReq) {
        userManager.updateUser(UserConverter.INSTANCE.convert(userUpdateReq));
        return success(true);
    }
}
